import * as FileSaver from 'file-saver'
// const Excel = require('exceljs')
// import * as Excel from 'exceljs'
import * as Excel from 'exceljs/dist/exceljs.min.js'

let workbook
let worksheet

function init () {
  workbook = new Excel.Workbook()
  workbook.created = new Date()
  workbook.modified = new Date()
  worksheet = workbook.addWorksheet('sheet1')
}
/**
 * @param url 图片路径
 * @param ext 图片格式
 */
function getUrlBase64 (url, ext) {
  return new Promise((resolve) => {
    let canvas = document.createElement('canvas') // 创建canvas DOM元素
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.crossOrigin = 'Anonymous'
    img.src = url
    img.onload = function () {
      canvas.height = img.height // 指定画板的高度,自定义
      canvas.width = img.width // 指定画板的宽度，自定义
      ctx.drawImage(img, 0, 0, img.width, img.height) // 参数可自定义
      const dataURL = canvas.toDataURL('image/' + ext)
      canvas = null
      resolve(dataURL) // Base64编码
    }
  })
}
/**
 * 获取单元格
 * **/
function getColumnNameByIndex (i) {
  let result = String.fromCharCode('A'.charCodeAt(0) + i % 26)
  while (i >= 26) {
    i /= 26
    i--
    result = String.fromCharCode('A'.charCodeAt(0) + i % 26) + result
  }
  return result
}

export const exportExcel = async (columns, Data, fileName) => {
  init()
  columns = columns.map((item) => {
    return Object.assign({}, {
      header: item.title,
      width: item.types === 'date' || item.types === 'image' ? 30 : 15
    },
    item
    )
  })
  worksheet.columns = columns

  // 顶部logo
  let imageId = ''
  await getUrlBase64('http://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/vip-entry.a14de9c.png', 'png').then(res => {
    imageId = workbook.addImage({
      base64: res,
      extension: 'jpeg'
    })
  })
  worksheet.insertRow(1)
  const len = getColumnNameByIndex((columns.length - 1)) + '1'

  worksheet.mergeCells('A1:' + len)
  worksheet.addImage(imageId, {
    tl: {
      col: 0,
      row: 0
    },
    ext: {
      width: 120,
      height: 30
    }
  })
  const headers = worksheet.getRow(1)
  headers.height = 30
  // 设置标题高度
  const title = worksheet.getRow(2)
  title.height = 22
  // 内容
  for (let i = 0; i < Data.length; i++) {
    const list = []
    const rowData = {}
    for (let j = 0; j < columns.length; j++) {
      if (columns[j].types === 'text' || columns[j].types === undefined) {
        rowData[columns[j].key] = Data[i][columns[j].key]
      } else if (columns[j].types === 'date') {
        rowData[columns[j].key] = (Data[i][columns[j].key])
      } else if (columns[j].types === 'image') {
        let imageId2 = ''
        await getUrlBase64(Data[i][columns[j].key], 'png').then(res => {
          imageId2 = workbook.addImage({
            base64: res,
            extension: 'jpeg'
          })
        })
        worksheet.addImage(imageId2, {
          tl: {
            col: 0.5 + j,
            row: 2.5 + i
          },
          ext: {
            width: 120,
            height: 30
          }
        })
      }
    }
    // 添加一行数据
    list.push(rowData)
    worksheet.addRows(list)
    // 获取最后一行
    const row = worksheet.lastRow
    // 设置特定的行高
    row.height = 30
    row.commit()
    // 设置单元格样式
    for (let n = 0; n < columns.length; n++) {
      const dobCol = worksheet.getColumn(n + 1)
      dobCol.eachCell(function (cell) { // 返回两个参数cell, rowNumber
        cell.alignment = {
          vertical: 'middle',
          horizontal: 'center'
        }
      })
    }
  }
  // 表尾
  const footerData = ['XXXX', '广州市天河区XXX街道XXX号', 'Tel: 202-10086; Fax:020-10086', 'Email: 123456@qq.com', 'Website: www.juejin.cn']
  for (let i = 0; i < footerData.length; i++) {
    const arr = []
    const obj = {}
    obj[columns[0].key] = footerData[i]
    // 添加一行数据
    arr.push(obj)
    worksheet.addRows(arr)
    // 获取最后一行
    const row = worksheet.lastRow
    // 设置特定的行高
    row.height = 22
    const flen = getColumnNameByIndex((columns.length - 1)) + row._number
    worksheet.mergeCells('A' + row._number + ':' + flen)
    row.commit()
    const dobCol = worksheet.getColumn(1)
    dobCol.eachCell(function (cell) {
      cell.alignment = {
        vertical: 'middle'
      }
    })
  }
  workbook.xlsx.writeBuffer().then((buffer) => {
    try {
      FileSaver.saveAs(
        new Blob([buffer], {
          type: 'application/octet-stream'
        }),
        fileName + '.' + 'xlsx'
      )
    } catch (e) {
      if (typeof console !== 'undefined') console.log(e, buffer)
    }
  })
}
